package com.example.java_chatroom_redis_rabbitmq.controller;

import com.example.java_chatroom_redis_rabbitmq.model.NewFriend;
import com.example.java_chatroom_redis_rabbitmq.model.Result;
import com.example.java_chatroom_redis_rabbitmq.model.Session;
import com.example.java_chatroom_redis_rabbitmq.model.User;
import com.example.java_chatroom_redis_rabbitmq.service.FriendService;
import com.example.java_chatroom_redis_rabbitmq.service.NewFriendService;
import com.example.java_chatroom_redis_rabbitmq.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/newFriend")
@RestController
public class NewFriendController {
    @Autowired
    private NewFriendService newFriendService;
    @Autowired
    private FriendService friendService;

    @Autowired
    private SessionService sessionService;

    @Transactional
    @RequestMapping("/allow")
    public Result<Integer> allow(Integer friendId, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        Integer ret = friendService.addFriend(user.getUserId(), friendId);
        if (ret <= 0) return Result.fail(500,-1,"服务器内部出现错误，请联系管理员!");
        ret = newFriendService.deleteNewFriend(friendId,user.getUserId());
        if (ret <= 0) return Result.fail(500,-1,"服务器内部出现错误，请联系管理员!");
        Session session1 = new Session();
        ret = sessionService.createSession(session1);
        if (ret > 0) {
            return Result.success(session1.getSessionId());
        }else {
            return Result.fail(500,-1,"服务器内部出现错误，请联系管理员!");
        }
    }

    @RequestMapping("/reject")
    public Result<Boolean> reject(Integer friendId,HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        Integer ret = newFriendService.deleteNewFriend(friendId,user.getUserId());
        if (ret <= 0) return Result.fail(500,false,"服务器内部出现错误，请联系管理员!");
        return Result.success(true);
    }

    @RequestMapping("/getNewFriendList")
    public Result<List<NewFriend>> getNewFriendList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        List<NewFriend> ret = newFriendService.getNewFriendList(user.getUserId());
        return Result.success(ret);
    }
}
